package com.kayt.cyberBar.cpublic.business.dao.impl;

import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.kayt.cyberBar.common.PageData;
import com.kayt.cyberBar.common.dao.EntityDao;
import com.kayt.cyberBar.cpublic.business.dao.IPublicKeyDao;
import com.kayt.cyberBar.cpublic.business.entity.po.CPublicKey;

@Repository("iPublicKeyDao")
public class PublicKeyDaoImpl implements IPublicKeyDao {
	@Autowired
	private EntityDao entityDao;

	@Override
	public Long addKey(CPublicKey key) throws SQLException {
		if (key != null) {
			return this.entityDao.save(key);
		}
		return 0L;
	}
	
	@Override
	public void updateKey (CPublicKey key) throws SQLException {
		if (key != null) {
			this.entityDao.update(key);
		}
	}
	
	@Override
	public void batchInsert (List<CPublicKey> itemList) {
		this.entityDao.batchInsert(itemList);
	}
	
	@Override
	public int deleteKey (CPublicKey key) {
		if (key != null) {
			this.entityDao.deleteDetached(key);
			return 0;
		}
		return -1;
	}
	
	@Override
	public CPublicKey getKey (String keyId) {
		CPublicKey bCompanyKey = null;
		if (keyId != null) {
			Long id;
			try {
				id = Long.parseLong(keyId);
			} catch (Exception e) {
				return null;
			}
			bCompanyKey = this.entityDao.findById(id, CPublicKey.class);
		}
		return bCompanyKey;
	}
	
	@Override
	public CPublicKey getKeyByCode (String paramCode) throws SQLException {
		CPublicKey bCompanyKey = null;
		if (paramCode != null) {
			bCompanyKey = this.entityDao.getObj(CPublicKey.class, " o.paramCode=? ", new Object[]{paramCode});
		}
		return bCompanyKey;
	}
	
	@Override
	public PageData<CPublicKey> getKeyList (int pageNum, int pageSize, String hql, Object[] params, LinkedHashMap<String, String> keyMap) throws SQLException {
		return this.entityDao.getPagingData(CPublicKey.class, pageNum, pageSize, hql, params, keyMap);
	}
	
	@Override
	public List getKeyListByHql(int pageNum, int pageSize, String hql, Object[] params) throws SQLException {
		return this.entityDao.getPagingDataByHql(pageNum, pageSize, hql, params);
	}

	@Override
	public boolean checkValidate(String paramKey, String paramValue) throws SQLException {
		if (StringUtils.isNotBlank(paramKey)) {
			String hql = "select count(o.id) as count from CPublicKey o where o.paramKey=? and o.paramValue=? ";
	        List countListMap = this.entityDao.getPagingDataByHql(-1, -1, hql, new Object[]{paramKey, paramValue});
	        if(countListMap != null && !countListMap.isEmpty()) {
	            Map countMap = (Map)countListMap.get(0);
	            Long tempCount = (Long)countMap.get("count");
	            if (tempCount.intValue() == 0) {
	            	return true;
	            }
	        }
		}
		return false;
	}
}
